package jmine.tec.proxy.builder;

import java.lang.reflect.Proxy;

import jmine.tec.proxy.AbstractProxyBuilder;
import jmine.tec.proxy.ProxyBuilder;
import jmine.tec.proxy.chain.ChainElement;
import jmine.tec.proxy.chain.ChainedInvocationHandler;

/**
 * ProxyBuilder that uses JDKProxy
 * @author MarceloT
 */
public class JDKProxyBuilder extends AbstractProxyBuilder implements ProxyBuilder {

    private Object delegate;

    private ChainElement[] elements = new ChainElement[0];

    /**
     * @return Object
     */
    public Object build() {
        final ChainedInvocationHandler ih = new ChainedInvocationHandler(delegate, elements);
        final Class<?>[] allInterfaces = collectAllInterfaces();
        return Proxy.newProxyInstance(this.getClass().getClassLoader(), allInterfaces, ih);
    }

    /**
     * @param els the elements
     */
    public void setChainElements(ChainElement... els) {
        this.elements = els;
    }

    /**
     * @param delegate the delegate
     */
    public void setDelegate(Object delegate) {
        this.delegate = delegate;
        if (delegate != null) {
            this.addInterfacesFrom(delegate.getClass());
        }
    }

    /**
     * @param type the type
     */
    @Override
    public void doSetMainType(Class<?> type) {
        if (!type.isInterface()) {
            throw new IllegalArgumentException("Only accepts interfaces");
        }
    }

}
